package com.lh.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.uuid.impl.UUIDUtil;
import com.lh.controller.DsmsUserController;
import com.lh.entity.table.DsmsUser;
import com.lh.entity.table.ReminderInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class HuangGangUtil {
//    appId： HGS_JJYXDDPT
//- 接口地址： https://gateway.ihuanggang.cn/ee6316bf-ba0b-42c1-8c6f-640db684c4bc
//AES密钥： c7bo5l4buf0ladsu
//- x-hg-api-key： 1830ee2c-3be2-4a23-b725-c16b12097203
//- jssdk地址： https://kfpt.ihuanggang.cn/jssdk/js/jssdk.js
    private static final Logger log = LoggerFactory.getLogger(HuangGangUtil.class);

    private static final String appId = "HGS_JJYXDDPT";

    private static final String AESKEY = "c7bo5l4buf0ladsu";

    //https://gateway.ihuanggang.cn/84a6de26dd0f5ec283618a7d91682535
//    private static final String BASEURL = "https://gateway.ihuanggang.cn/84a6de26dd0f5ec283618a7d91682535";
    private static final String BASEURL = "https://gateway.ihuanggang.cn/ee6316bf-ba0b-42c1-8c6f-640db684c4bc";
    private static final String APIKEY = "1830ee2c-3be2-4a23-b725-c16b12097203";


    public static String generateRandomNumber(int length) {
        if (length <= 0) {
            throw new IllegalArgumentException("Length must be greater than 0");
        }

        StringBuilder sb = new StringBuilder(length);
        Random random = new Random();

        for (int i = 0; i < length; i++) {
            int digit = random.nextInt(10); // 生成0到9之间的随机整数
            sb.append(digit);
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        String signValue = "MIIGGAYKKoEcz1UGAQQCAqCCBggwggYEAgEBMQ4wDAYIKoEcz1UBgxEFADATBgoqgRzPVQYBBAIBoAUEAzExMqCCBMUwggTBMIIEZqADAgECAggBRdw35wUf7zAMBggqgRzP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S4reW/g+aciemZkOWFrOWPuCxvPWh1bmNhP2NlcnRpZmljYXRlUmV2b2NhdGlvbkxpc3Q/YmFzZT9vYmplY3RjbGFzcz1jUkxEaXN0cmlidXRpb25Qb2ludDBQBggrBgEFBQcBAQREMEIwQAYIKwYBBQUHMAKGNGh0dHA6Ly8yMjIuMjQwLjE4LjM3OjI4ODg4L3B1YmxpYy9zbTIvSFVOQU5DQVNNMi5wN2IwbQYDVR0gBGYwZDBiBgoqgRyG7xcBAQEBMFQwUgYIKwYBBQUHAgEWRmh0dHA6Ly93d3cuaHVuY2EuY29tLmNuL2ludHJvZHVjdGlvbi8yMDEyMDMvUDAyMDE5MDkyNDQyNjczOTc3MDk3MS5wZGYwDAYIKoEcz1UBg3UFAANHADBEAiAR39sxcwt5ghuqwfCsRLuhfH8u90sxyzu+Kzr/MzdFHwIgYKIctyVSPFnAXGFJ2NGVhRs1zJplpDyWWMtQQrDZ7nMxggEPMIIBCwIBATCBnzCBkjELMAkGA1UEBhMCQ04xEjAQBgNVBAgMCea5luWNl+ecgTESMBAGA1UEBwwJ6ZW/5rKZ5biCMTYwNAYDVQQKDC3muZbljZfnnIHmlbDlrZforqTor4HmnI3liqHkuK3lv4PmnInpmZDlhazlj7gxDjAMBgNVBAsMBUhVTkNBMRMwEQYDVQQDDApIVU5BTkNBU00yAggBRdw35wUf7zAMBggqgRzPVQGDEQUAMA0GCSqBHM9VAYItAQUABEcwRQIhAP1XdH4Zc223IRpj8j9xWh/lX8vZuwznCR+ISxAiNUxAAiAOXACgKeZ212E1hMe4Rrzrz5FXFI1y0543Inaiu3GvCQ==";
        String transId = generateRandomNumber(16);
        getAesResult(signValue,transId,"","");
    }


    public static String getAesResult(String signValue,String transId,String signature,String deviceId){
//        - 测试接口地址：
        // 1. 获取
        System.out.println("signValue");
        System.out.println(signValue);
        System.out.println(signature);
        System.out.println(deviceId);
        // 假设这是BJCA颁发的密钥
        JSONObject paramsJson = new JSONObject();
        paramsJson.put("appId", "APP_D82E9FC635FA45E89BB8072948B6826D");
        paramsJson.put("deviceId", deviceId);
        paramsJson.put("version", "1");
        paramsJson.put("signAlgo", "HmacSHA256");
        paramsJson.put("transId",transId);
        paramsJson.put("oriData","112");
        paramsJson.put("verifyCert",false);
        paramsJson.put("signValue",signValue);
        paramsJson.put("signature",signature);
        log.info(paramsJson.toJSONString());
        String result = HttpPostClient.sendPostJson("http://100.131.200.17:10006/dsvs/v1/pkcs7/verifyDataSign",paramsJson.toJSONString());
        JSONObject jsonObject = JSONObject.parseObject(result);
        log.info(jsonObject.toJSONString());
//        {"code":1,"status":200,"msg":"操作成功","data":"_ihg_0e8f388e2a8e4eec941735aaac338b9a_ihg_","encrypt":false,"algorithm":0,"key":null,"reqId":null,"rsa":false}
        if (jsonObject!=null && jsonObject.getJSONObject("data")!=null){
            JSONObject JB22 = jsonObject.getJSONObject("data");
            String result22 = JB22.getString("result");
            return result22;
        }
        return null;
    }


    // Jackson ObjectMapper用于解析JSON
    /**
     * 计算签名的主方法
     * @param data 包含请求参数的Map
     * @param secret 密钥
     * @return 计算得到的签名
     * @throws Exception 加密过程中可能出现的异常
     */
    public static String calcSign(Map<String, Object> data, String secret) throws Exception {
        // 移除可能存在的signature字段
        data.remove("signature");

        // 对参数名进行排序
        TreeMap<String, Object> sortedData = new TreeMap<>(data);

        // 拼接key=value字符串，跳过空值
        StringBuilder kvStr = new StringBuilder();
        for (Map.Entry<String, Object> entry : sortedData.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();

            // 跳过空值和空字符串
            if (key.equals("signature")|| value == null || "".equals(value.toString().trim())) {
                continue;
            }

            if (kvStr.length() > 0) {
                kvStr.append("&");
            }
            kvStr.append(key).append("=").append(value);
        }
        System.out.println(kvStr.toString());
        // 指定HMAC算法为SHA256
        String algorithm = "HmacSHA256";
        // 创建HMAC密钥规范
        SecretKeySpec secretKeySpec = new SecretKeySpec(
                secret.getBytes(StandardCharsets.UTF_8),
                algorithm
        );

        // 获取Mac实例并初始化
        Mac mac = Mac.getInstance(algorithm);
        mac.init(secretKeySpec);
        // 计算HMAC-SHA256哈希值
        byte[] hmacBytes = mac.doFinal(kvStr.toString().getBytes(StandardCharsets.UTF_8));
        // 对哈希结果进行Base64编码
        return Base64.getEncoder().encodeToString(hmacBytes);
    }

    /**
     * 解析URL参数为Map
     * @param url 包含参数的URL
     * @return 解析后的参数Map
     */
    public static Map<String, Object> getUrlVars(String url) {
        if (url == null || !url.contains("?")) {
            return new HashMap<>();
        }

        String queryString = url.substring(url.indexOf('?') + 1);
        String[] paramPairs = queryString.split("&");
        Map<String, Object> params = new HashMap<>();

        for (String pair : paramPairs) {
            String[] keyValue = pair.split("=", 2);
            if (keyValue.length == 2) {
                params.put(keyValue[0], keyValue[1]);
            } else if (keyValue.length == 1) {
                params.put(keyValue[0], "");
            }
        }

        return params;
    }

    public static String login(String oToken){
        String result = HuangGangPtReqUtil.httpRequest(BASEURL,APIKEY,oToken);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject!=null && jsonObject.getString("data")!=null){
            String data = jsonObject.getString("data");
            try {
                String aesRes = AESUtil.decrypt(data,AESKEY);
                return aesRes;
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }

        return result;
    }

    public static String sendMsg(ReminderInfo hgReminderData){
//        - 测试接口地址：
//        http://hgcity-dev.chutianyun.gov.cn:8016/gateway/2f8c7265c4274eca92ec1b583b34fa0d
//        - 正式接口地址： https://gateway.ihuanggang.cn/2f8c7265c4274eca92ec1b583b34fa0d
//        - x-hg-api-key： 13ded457-66f4-4f1d-abb9-df25cc936ebf
        String postUrl = "https://gateway.ihuanggang.cn/2f8c7265c4274eca92ec1b583b34fa0d";
        String apiKey = "13ded457-66f4-4f1d-abb9-df25cc936ebf";
        JSONObject jsObj = new JSONObject();
        jsObj.put("title",hgReminderData.getReminderTitle());
        jsObj.put("source","黄冈市经济运行调度平台");
        jsObj.put("introduction",hgReminderData.getReminderContent());
        jsObj.put("userId",hgReminderData.getIHgUser());
        jsObj.put("messType",1);
        jsObj.put("pushObj",1);
        jsObj.put("linkType",1);
        jsObj.put("pushType",3);
        jsObj.put("linkUrl","http://36.133.17.156:18090/phone/#/");
        String jsonStrParam = jsObj.toJSONString();
        String result = HuangGangPtReqUtil.httpsRequestJson(postUrl,apiKey,jsonStrParam);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject!=null && jsonObject.getString("data")!=null){
            String data = jsonObject.getString("data");
            try {
                return "";
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }

        return result;
    }

    public static String sendJyMsg(ReminderInfo hgReminderData){
//        - 测试接口地址：
//        http://hgcity-dev.chutianyun.gov.cn:8016/gateway/2f8c7265c4274eca92ec1b583b34fa0d
//        - 正式接口地址： https://gateway.ihuanggang.cn/2f8c7265c4274eca92ec1b583b34fa0d
//        - x-hg-api-key： 13ded457-66f4-4f1d-abb9-df25cc936ebf
        String postUrl = "https://gateway.ihuanggang.cn/2f8c7265c4274eca92ec1b583b34fa0d";
        String apiKey = "13ded457-66f4-4f1d-abb9-df25cc936ebf";
        JSONObject jsObj = new JSONObject();
        jsObj.put("title",hgReminderData.getReminderTitle());
        jsObj.put("source","学习教育集中整改整治工作调度");
        jsObj.put("introduction",hgReminderData.getReminderContent());
        jsObj.put("userId",hgReminderData.getIHgUser());
        jsObj.put("messType",1);
        jsObj.put("pushObj",1);
        jsObj.put("linkType",1);
        jsObj.put("pushType",3);
        jsObj.put("linkUrl","http://59.110.44.78:18092/");
        String jsonStrParam = jsObj.toJSONString();
        String result = HuangGangPtReqUtil.httpsRequestJson(postUrl,apiKey,jsonStrParam);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject!=null && jsonObject.getString("data")!=null){
            String data = jsonObject.getString("data");
            try {
                return "";
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }

        return result;
    }



    public static String syncUser(){
        //hgcityCore/home/floatWindowUser
//        张章，蔡宁，杨文志，方为美，皮李星
//        String[] names = {
//                "caining", "chendan", "chenjun", "chenzhenghong", "dengzhonglin",
//                "fangweimei", "gaoweipeng", "haoaifang", "huananyuan", "huguang",
//                "huhao", "hukai", "lichumin", "lijunjie", "liling",
//                "liaojinjun", "liujie", "liutangjun", "liuting", "liuyuxiao",
//                "liuzhongcheng", "maliang", "mayanzhou", "panguolin", "peiyongbo",
//                "xiazhidong", "zhangzhang", "zhaoxiaohu", "zhengguangwen", "zhouli",
//                "yidong", "fengzhiqi" ,"wangxiaobing","tangzhen"
//        };
//        String[] phones = {
//                "15972836299", "18672158196", "15871818999", "13907259080", "13872034288",
//                "18186355688", "13971718061", "13508655326", "15907255899", "18120325835",
//                "13707252908", "18907255888", "13339966557", "13907160801", "18872726966",
//                "18871335577", "13607172207", "13907256006", "13409808499", "13508657728",
//                "13972132636", "13971705274", "13971703676", "15807251168", "15997340232",
//                "13907250667", "13871969999", "13409690362", "13907251618", "13659841123",
//                "18872714299", "16602722600", "15997347209", "15387192637"
//        };
        String[] names = {
                "caining", "fangweimei", "zhangzhang", "yangwenzhi","luoyan",
                "yidong", "fengzhiqi" ,"wangxiaobing","tangzhen","shaoshanyang",
                "yanglei", "hejingxin", "liuyong","jinleijun","fanxueao","yanzhefeng",
                "18972749999","18062211070","18942142266","13636012466","13260644663",
                "18696070901","18671350177","13477668900","13307250175",
                "13872021268", "13971730706", "15907131466", "13871995955"

        };
        String[] phones = {
                "15972836299", "18186355688", "13871969999","18086667678","18827468989",
                "18872714299", "16602722600", "15997347209", "15387192637","18995759186",
                "15098008201", "15926304883", "18171770913","18064172185","13277202000",
                "18907251696","18972749999","18062211070","18942142266","13636012466",
                "13260644663","18696070901","18671350177","13477668900","13307250175",
                "13872021268", "13971730706", "15907131466", "13871995955"
        };
        StringBuilder json = new StringBuilder("[");
        for (int i = 0; i < names.length; i++) {
            if (i > 0) {
                json.append(",");
            }
            json.append("{")
                    .append("\"userName\":\"").append(names[i]).append("\",")
                    .append("\"phoneNum\":\"").append(phones[i]).append("\"")
                    .append("}");
        }
        json.append("]");
        String postJson = json.toString();
        String key = "y8JiwSDcp09JKvr7";
        String iv = "0102030405060711";
        try {
            postJson = AESUtil.encryptAES(postJson, key, iv);
            System.out.println("data: " + postJson);
            //https://gateway.ihuanggang.cn/84a6de26dd0f5ec283618a7d91682535
            String url = "https://gateway.ihuanggang.cn/84a6de26dd0f5ec283618a7d91682535";
//            String url = "http://hgcity-dev.chutianyun.gov.cn:8016/hgapp-core/hgcityCore/home/floatWindowUser";
            JSONObject reqObj = new JSONObject();
            reqObj.put("data",postJson);
            String result = HuangGangPtReqUtil.httpJson(url,reqObj.toJSONString());
            System.out.println("result: " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        String result = HuangGangPtReqUtil.httpRequest(BASEURL,APIKEY,oToken);
//        JSONObject jsonObject = JSONObject.parseObject(result);
//        if (jsonObject!=null && jsonObject.getString("data")!=null){
//            String data = jsonObject.getString("data");
//            try {
//                String aesRes = AESUtil.decrypt(data,AESKEY);
//                return aesRes;
//            } catch (Exception e) {
//                e.printStackTrace();
//                throw new RuntimeException(e);
//            }
//        }

        return postJson;
    }


    public static void syncUserList(List<DsmsUser> hgUserList) {
        StringBuilder json = new StringBuilder("[");
        for (int i = 0; i < hgUserList.size(); i++) {
            if (i > 0) {
                json.append(",");
            }
            json.append("{")
                    .append("\"userName\":\"").append(hgUserList.get(i).getUserName()).append("\",")
                    .append("\"phoneNum\":\"").append(hgUserList.get(i).getMobileNo()).append("\"")
                    .append("}");
        }
        json.append("]");
        String postJson = json.toString();
        String key = "y8JiwSDcp09JKvr7";
        String iv = "0102030405060711";
        try {
            postJson = AESUtil.encryptAES(postJson, key, iv);
            System.out.println("data: " + postJson);
            String url = "https://gateway.ihuanggang.cn/84a6de26dd0f5ec283618a7d91682535";
            JSONObject reqObj = new JSONObject();
            reqObj.put("data",postJson);
            String result = HuangGangPtReqUtil.httpJson(url,reqObj.toJSONString());
            System.out.println("result: " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
